package shc.graduation.http;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import shc.graduation.utils.log.LogUtils;

/**
 * Created by shuhuiChen on  2016/5/21  14:25.
 * Email ：shuhuiCSH@126.com
 */
public class HttpGetContent implements IHttpGetContent {
    private static HttpClient mHttpClient = null;
    private String encode = "utf-8";

    public static synchronized HttpClient getInstanceClient() {
        if (mHttpClient == null) {
            mHttpClient = new DefaultHttpClient();
        }
        return mHttpClient;
    }

    @Override
    public String getContent(final String url) {

        LogUtils.e("HttpGetContent:" + url);

        String response = null;
        StringBuilder sb = new StringBuilder();

        HttpGet get = new HttpGet(url);
        HttpResponse httpResponse = null;
        try {
            httpResponse = HttpGetContent.getInstanceClient().execute(get);
            HttpEntity entity = httpResponse.getEntity();

            if (entity != null) {

                BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent(), encode));
                while ((response = br.readLine()) != null) {
                    sb.append(response);
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
            LogUtils.e("网络异常：" + e.getMessage());
            return null;
        }

        return sb.toString();
    }

    @Override
    public void setEncode(String encode) {
        this.encode = encode;
    }
}
